<?php


class wsTask
{
    const HOST = '0.0.0.0';
    const PORT = 9501;

    public $ws = null;

    public function __construct()
    {
        $this->ws = new swoole_websocket_server(static::HOST, static::PORT);

        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('close', [$this, 'onClose']);
        $this->ws->on('task', [$this, 'onTask']);
        $this->ws->on('finish', [$this, 'onFinish']);

        $this->ws->start();
    }

    /**
     * 监听连接事件
     * @param $ws
     * @param $request
     */
    public function onOpen($ws, $request) {
//        var_dump($request->fd);
        echo "客户端{$request->fd}和服务端握手成功";
    }

    /**
     * 监听消息接收事件
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws, $frame) {
        echo "服务端收到消息如下:{$frame->data}\n";
        // 模拟一个耗时3s的操作,猜猜程序是否是等待了3s
        $data = [
            'message'   => '邮件发送成功',
            'fd'        => $frame->fd,
        ];
        $ws->task($data);

        // 消息推送给客户端
        $ws->push($frame->fd, "server-push:" . date('Y-m-d H:i:s'));
    }

    /**
     * 监听关闭事件
     * @param $ws
     * @param $fd
     */
    public function onClose($ws, $fd) {
        echo "客户端{$fd}关闭\n";
    }

    /**
     * 监听task事件
     * @param $ws
     * @param $taskId
     * @param $workerId
     * @param $data
     * @return string
     */
    public function onTask($ws, $taskId, $workerId, $data) {
        var_dump($data);
        // 耗时场景
        sleep(3);
        // 返回给worker进程,由finish接收
        return "on 04_task finish"; // 等效于 $ws->finish("on 04_task finish");
    }

    /**
     * 监听task finish事件
     * @param $ws
     * @param $taskId
     * @param $data
     */
    public function onFinish($ws, $taskId, $data) {
        // 这里的$data 是 04_task return 的数据
        var_dump($data);
    }
}

$ws = new wsTask();